#include "browseview.h"
#include <QGraphicsPixmapItem>
#include "toolkit.h"
#include <QDir>
#include "commondef.h"
#include <QMouseEvent>
#include <QDebug>
#include "browsesingleview.h"
#include "imageitem.h"
#include <qmath.h>
#include "QProgressIndicator.h"
#include <QTimer>

enum BrowsePressType
{
    NULL_BTP,
    BACK_BTP
}BPressTp(NULL_BTP);

BrowseView::BrowseView(QWidget *parent) :
    QGraphicsView(parent),
    m_iStartY(0),
    m_bmove(false),
    m_bsupportmove(false),
    m_selectitem(NULL),
    m_BrowsesingleView(NULL),
    m_pi(NULL)
{
    m_Scene = new QGraphicsScene(this);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setScene(m_Scene);
    m_Scene->setSceneRect(0.0, 0.0, 640.0, 360.0);

    m_backItem = new ImageItem(QImage(":/image/567.282.png","png"),
                               QRect(QPoint(0,0),QImage(":/image/567.282.png","png").size()));
    m_backItem->setPos(568,282);
    m_backItem->setZValue(2.0);
    m_Scene->addItem(m_backItem);

    m_bgItem = new ImageItem(QImage(":/image/BG.png","png"),
                             QRect(QPoint(0,0),QImage(":/image/BG.png","png").size()));
    m_bgItem->setPos(0,0);
    m_bgItem->setZValue(0.0);
    m_Scene->addItem(m_bgItem);

    m_borderImage.load(":/image/c_015.png","png");

    ToolKit::m_browseView = this;

    LoadImages();
}

BrowseView::~BrowseView()
{
    delete m_Scene;

    if(!m_itemlist.isEmpty())
    {
        m_itemlist.clear();
    }
}

void BrowseView::RunThread()
{
    PIXMAPITEM* pItem = 0;
    for(int i=0; i <m_itemlist.size();i++)
    {
        if( pItem = &m_itemlist[i] )
        {
            delete pItem;
            pItem = NULL;
        }
    }
    m_itemlist.clear();

    QDir dir(ToolKit::m_path,"",QDir::Time);
    if( !dir.exists())
        return;

    dir.setFilter(QDir::Files);
    QFileInfoList list = dir.entryInfoList();

    QImage image;
    int irow(0),iline(0);
    for(int i=0; i< list.size();i++)
    {
        QFileInfo fileInfo = list.at(i);
        QString strext = fileInfo.suffix().toLower();
        if(strext != "png")
            continue;

        if( image.load(fileInfo.absoluteFilePath(),"png"))
        {
            image = image.scaled(QSize(130,90),Qt::IgnoreAspectRatio);
            QImage ComposeImage(134,94,QImage::Format_ARGB32);
            ComposeImage.fill(0);
            QPainter painter(&ComposeImage);

            DrawCorner(image);

            painter.drawImage(QRectF(2.0,2.0,130.0,90.0),image);
            painter.drawImage(QRectF(0.0,0.0,134.0,94.0),m_borderImage);

            PIXMAPITEM iItem;
            iItem.item = new ImageItem(ComposeImage,QRect(QPoint(0,0),ComposeImage.size()));
            iItem.item->setPos(BROSE_ORIGIN_X + BROSE_ROW_DISTANCE * irow++,
                                BROSE_ORIGIN_Y + BROSE_LINE_DISTANCE * iline);
            iItem.item->setZValue(1.0);
            m_Scene->addItem(iItem.item);

            iItem.strPath = fileInfo.absoluteFilePath();

            m_itemlist.append(iItem);

            if(irow % 4 == 0)
            {
                irow = 0;
                ++iline;
            }
        }
    }

    if(iline > 2)
    {
        m_bsupportmove = true;
    }

    if(m_pi != NULL)
    {
        m_pi->stopAnimation();
        delete m_pi;
        m_pi = NULL;
    }
}

void BrowseView::LoadImages()
{
    if(m_pi == NULL)
    {
        m_pi = new QProgressIndicator(this);
        m_pi->setWindowModality(Qt::WindowModal);
        m_pi->raise();
        m_pi->setGeometry(270,131,100,100);
        m_pi->startAnimation();
        m_pi->show();
    }

    QTimer::singleShot(1000,this,SLOT(RunThread()));
}

void BrowseView::mousePressEvent(QMouseEvent *event)
{
    if(m_backItem->isUnderMouse())
    {
        BPressTp = BACK_BTP;
    }
    else
    {
        BPressTp = NULL_BTP;
        m_iStartY = event->pos().y();
        QList<QGraphicsItem *> itemlist = items(event->pos());
        if(itemlist.count() == 2)
        {
            m_selectitem = (ImageItem*)itemlist.at(0);
        }
    }
}

void BrowseView::mouseMoveEvent(QMouseEvent *event)
{
    if(m_bsupportmove)
    {
        int imove = event->pos().y() - m_iStartY;
        if(m_bmove)
        {
            PIXMAPITEM* firstitem = &m_itemlist.first();
            PIXMAPITEM* lastitem = &m_itemlist.last();

            if(firstitem->item->y() > BROSE_ORIGIN_Y)
            {
                int irow = 0;
                int iline = 0;

                foreach(PIXMAPITEM item,m_itemlist)
                {
                    item.item->setY(BROSE_ORIGIN_Y + BROSE_LINE_DISTANCE * iline);

                    ++irow;
                    if(irow % 4 == 0)
                    {
                        irow = 0;
                        ++iline;
                    }
                }

                m_bmove = false;
            }
            else if(lastitem->item->y() < 248)
            {
                int imove = 248 - lastitem->item->y();

                foreach(PIXMAPITEM item,m_itemlist)
                {
                    item.item->setY(item.item->y() + imove);
                }

                m_bmove = false;
            }
            else
            {
                foreach(PIXMAPITEM item,m_itemlist)
                {
                    item.item->setY(item.item->y() + imove);
                }
            }
            m_iStartY = event->pos().y();
        }
        else
        {
            if(abs(imove) > SHAKE_PARA)
            {
                m_iStartY = event->pos().y();
                m_bmove = true;
            }
        }

    }
}

void BrowseView::mouseReleaseEvent(QMouseEvent *event)
{
    switch(BPressTp)
    {
    case BACK_BTP:
    {
        emit back();
        BPressTp = NULL_BTP;
    }
        break;
    case NULL_BTP:
    {
        if(m_bmove)
        {
            m_bmove = false;
        }
        else
        {
            QList<QGraphicsItem *> itemlist = items(event->pos());
            if(itemlist.count() == 2)
            {
                if(m_selectitem == itemlist.at(0))
                {
                    for(int i = 0; i < m_itemlist.count(); ++i)
                    {
                        if(m_itemlist.at(i).item == m_selectitem)
                        {
                            ToolKit::m_strSelImage = m_itemlist.at(i).strPath;
                            ToolKit::m_icurIndex = i;

                            if(m_BrowsesingleView == NULL)
                            {
                                m_BrowsesingleView = new BrowsesingleView(this);
                                m_BrowsesingleView->setGeometry(0,0,640,360);
                                m_BrowsesingleView->showFullScreen();
                                connect(m_BrowsesingleView,SIGNAL(back()),this,SLOT(BrowseSingleViewBack()));
                            }

                            break;
                        }
                    }
                }
            }
        }
    }
        break;
    default:
        break;
    }
}

void BrowseView::DrawCorner(QImage &image)
{
    QImage mould(":/image/mould.png","png");

    uint* imagedata = (uint*)image.bits();
    uint* moulddata = (uint*)mould.bits();

    for(int i = 0; i < image.byteCount()>>2; ++i)
    {
        imagedata[i] &= 0x00ffffff;
        moulddata[i] &= 0xff000000;
        imagedata[i] |= moulddata[i];
    }
}

void BrowseView::BrowseSingleViewBack()
{
    if(m_BrowsesingleView != NULL)
    {
        delete m_BrowsesingleView;
        m_BrowsesingleView = NULL;
    }
}

void BrowseView::ResetItemPos()
{
    int irow = 0;
    int iline = 0;

    foreach(PIXMAPITEM item,m_itemlist)
    {
        item.item->setPos(BROSE_ORIGIN_X + BROSE_ROW_DISTANCE * irow++,
                          BROSE_ORIGIN_Y + BROSE_LINE_DISTANCE * iline);

        if(irow % 4 == 0)
        {
            irow = 0;
            ++iline;
        }
    }

    m_bsupportmove = iline > 2 ? true : false;
}
